from db_RehabSystem import *
from db_RehabSystem import RehabSystem as rs
from db_userManager import *


class RehabSystem:
    def __init__(self):
        """
        康复系统核心后端（修正版）
        移除循环引用，简化初始化流程
        初始化子模块（注意：不再递归创建实例）
        初始化缓存
        """
        self.DeviceManager = DeviceManager()
        self.userManager = UserManager()
        self.RehabSystem=rs()
        self._active_devices = None
        self._user_cache = {}

    def get_role_dashboard_data(self, user_id, role):
        """
        获取角色专属仪表盘数据
        参数:
            user_id: 用户ID
            role: 用户角色(doctor/therapist/patient)
        返回:
            字典格式的仪表盘数据
        """
        return self.RehabSystem.get_role_dashboard_data(user_id, role)

    def delete_device(self, therapist_id, device_id):
        """删除设备业务逻辑"""
        try:
            if not self.userManager.is_therapist(therapist_id):
                return False, "无权限删除设备"
            if not self.DeviceManager.device_exists(device_id):
                return False, f"设备 {device_id} 不存在"
            success = self.DeviceManager.delete_device(device_id)
            return (True, "设备删除成功") if success else (False, "设备删除失败")
        except Exception as e:
            print(f"删除设备异常: {e}")
            return False, "系统错误，删除设备失败"

    def add_new_device(self, therapist_id, device_data):
        """
        添加新设备
        参数:
            therapist_id: 治疗师ID
            device_data: 设备信息字典
        返回:
            (success, message) 元组
        """
        try:
            # 1. 验证治疗师权限
            if not self.userManager.is_therapist(therapist_id):
                return False, "无权限添加设备"
            # 2. 验证设备是否存在
            if self.DeviceManager.device_exists(device_data["device_id"]):
                return False, f"设备 {device_data['device_id']} 存在"
            # 2. 调用设备管理器
            success = self.DeviceManager.add_new_device(
                device_id=device_data["device_id"],
                device_type=device_data["device_type"],
                status=device_data["status"],
                location=device_data["location"],
                calibration_date=device_data["last_calibration"],
                therapist_id=therapist_id  # 明确传递 therapist_id
            )
            return (True, "设备添加成功") if success else (False, "设备添加失败")
        except KeyError as e:
            print(f"设备数据字段缺失: {e}")
            return False, f"设备信息不完整: 缺少字段 {str(e)}"
        except Exception as e:
            print(f"添加设备异常: {e}")
            return False, "系统错误，添加设备失败"

    def edit_device(self, therapist_id, device_id, new_status, new_location):
        """
        编辑设备信息
        参数:
            therapist_id: 治疗师ID
            device_id: 设备ID
            new_status: 新状态
            new_location: 新位置
        返回:
            (success, message) 元组
        """
        try:
            # 1. 验证治疗师权限
            if not self.userManager.is_therapist(therapist_id):
                return False, "无权限修改设备信息"
            # 2. 验证设备是否存在
            if not self.DeviceManager.device_exists(device_id):
                return False, f"设备 {device_id} 不存在"
            # 3. 调用设备管理器更新数据
            success = self.DeviceManager.update_device(
                device_id=device_id,
                new_status=new_status,
                new_location=new_location,
                updated_by=therapist_id
            )
            return (True, "设备信息更新成功") if success else (False, "设备信息更新失败")
        except Exception as e:
            print(f"编辑设备异常: {e}")
            return False, "系统错误，编辑设备失败"


